﻿using SkiaSharp;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Storage;
using System.Diagnostics;
using System.IO;
using System.Reflection;
#if IOS
using UIKit;
using Foundation; // 解决 NSData 问题
#endif
#if ANDROID
using WaterFlow; 
#endif
// 在文件顶部添加
#if WINDOWS
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Input; // 添加这个命名空间
using Windows.UI.Input; // 添加这个命名空间
#endif
namespace WaterFlow
{
    public partial class MainPage : ContentPage
    {
        private byte[]? originalImageData;
        private byte[]? processedImageData; 
        private double currentScale = 1.0;
        private const double MinScale = 0.5;
        private const double MaxScale = 3.0;
        private Point lastMousePosition;
        public MainPage()
        {
            InitializeComponent(); SetupZoom();
        }
        private void SetupZoom()
        {
            // 通用捏合手势（移动端）
            var pinchGesture = new PinchGestureRecognizer();
            pinchGesture.PinchUpdated += OnPinchUpdated;
            PreviewImage.GestureRecognizers.Add(pinchGesture);

            // Windows平台鼠标滚轮处理
#if WINDOWS
        AttachWindowsWheelHandler();
#endif
        }
#if WINDOWS

private void AttachWindowsWheelHandler()
{
    PreviewImage.HandlerChanged += (s, e) =>
    {
        if (PreviewImage.Handler?.PlatformView is Microsoft.UI.Xaml.Controls.Image winUIImage)
        {
            winUIImage.PointerMoved += (sender, eArgs) => 
            {
                var point = eArgs.GetCurrentPoint(winUIImage);
                lastMousePosition = new Point(point.Position.X, point.Position.Y);
            };
            
            winUIImage.PointerWheelChanged += (sender, eArgs) =>
            {
                // 使用全局键盘状态检测
                var ctrlState = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(Windows.System.VirtualKey.Control);
                bool isCtrlPressed = (ctrlState & Windows.UI.Core.CoreVirtualKeyStates.Down) != 0;

                if (isCtrlPressed)
                {
                    var point = eArgs.GetCurrentPoint(winUIImage);
                    var delta = point.Properties.MouseWheelDelta;
                    var scaleFactor = delta > 0 ? 1.1 : 0.9;
                    
                    UpdateScale(scaleFactor, new Point(point.Position.X, point.Position.Y));
                    eArgs.Handled = true;
                }
            };
        }
    };
}
#endif

        private void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
        {
            switch (e.Status)
            {
                case GestureStatus.Started:
                    lastMousePosition = new Point(e.ScaleOrigin.X, e.ScaleOrigin.Y);
                    break;

                case GestureStatus.Running:
                    UpdateScale(e.Scale, lastMousePosition);
                    break;

                case GestureStatus.Completed:
                    currentScale = Math.Clamp(currentScale, MinScale, MaxScale);
                    break;
            }
        }

        private void UpdateScale(double scaleFactor, Point centerPoint)
        {
            try
            {
                // 计算相对锚点
                var relativeX = centerPoint.X / PreviewImage.Width;
                var relativeY = centerPoint.Y / PreviewImage.Height;

                // 应用缩放
                currentScale *= scaleFactor;
                currentScale = Math.Clamp(currentScale, MinScale, MaxScale);

                // 更新视图
                PreviewImage.AnchorX = relativeX;
                PreviewImage.AnchorY = relativeY;
                PreviewImage.Scale = currentScale;

                Debug.WriteLine($"当前缩放: {currentScale:F2} | 锚点: ({relativeX:F2}, {relativeY:F2})");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"缩放错误: {ex.Message}");
            }
        }

        // 重置缩放的核心逻辑
        private void ResetZoom_Clicked(object sender, EventArgs e)
        {
            try
            {
                // 重置缩放比例到1.0
                currentScale = 1.0;

                // 将锚点重置到图片中心（默认位置）
                PreviewImage.AnchorX = 0.5;
                PreviewImage.AnchorY = 0.5;

                // 应用缩放设置
                PreviewImage.Scale = currentScale;

                Debug.WriteLine($"缩放已重置 | 当前比例: {currentScale} | 锚点: ({PreviewImage.AnchorX}, {PreviewImage.AnchorY})");
            }
            catch (Exception ex)
            {
                // 输出详细错误日志
                Debug.WriteLine($"[ERROR] 重置失败 | 时间: {DateTime.Now:HH:mm:ss} | 异常类型: {ex.GetType().Name}");
                Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");

                // 可选：显示用户友好提示
                MainThread.BeginInvokeOnMainThread(async () =>
                {
                    await DisplayAlert("错误", "重置功能暂时不可用", "确定");
                });
            }
        }





























        private async void SelectFile_Clicked(object sender, EventArgs e)
        {
            try
            {
                var result = await FilePicker.Default.PickAsync(new PickOptions
                {
                    PickerTitle = "选择图片文件",
                    FileTypes = new FilePickerFileType(
                        new Dictionary<DevicePlatform, IEnumerable<string>>
                        {
                            { DevicePlatform.Android, new[] { "image/*" } },
                            { DevicePlatform.WinUI, new[] { ".jpg", ".png", ".jpeg" } },
                            { DevicePlatform.macOS, new[] { "jpg", "png", ".jpeg" } },
                            { DevicePlatform.iOS, new[] { "public.image" } }
                        })
                });

                if (result != null)
                {
                    using var stream = await result.OpenReadAsync();
                    originalImageData = new byte[stream.Length];
                    int bytesRead = 0;
                    int totalBytes = 0;

                    while (totalBytes < originalImageData.Length &&
                           (bytesRead = await stream.ReadAsync(originalImageData, totalBytes, originalImageData.Length - totalBytes)) > 0)
                    {
                        totalBytes += bytesRead;
                    }

                    PreviewImage.Source = ImageSource.FromStream(() => new MemoryStream(originalImageData));
                    PreviewImage.IsVisible = true;
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"选择文件失败: {ex.Message}", "确定");
            }
        }

        private async void Generate_Clicked(object sender, EventArgs e)
        {
            if (originalImageData == null)
            {
                await DisplayAlert("提示", "请先选择图片", "确定");
                return;
            }

            try
            {
                using var originalStream = new MemoryStream(originalImageData);
                var originalBitmap = SKBitmap.Decode(originalStream);

                var bitmap = new SKBitmap(originalBitmap.Width, originalBitmap.Height);
                using var canvas = new SKCanvas(bitmap);
                canvas.DrawBitmap(originalBitmap, 0, 0);

                var watermarkText = WatermarkText.Text + new string(' ', 6); // 带6个空格

                // 加载字体
                var typeface = SKTypeface.FromFamilyName("楷体", SKFontStyle.Normal) ?? SKTypeface.Default;

                using var paint = new SKPaint
                {
                    Color = SKColors.LightGray.WithAlpha(150),
                    TextAlign = SKTextAlign.Left,
                    Typeface = typeface,
                    IsAntialias = true,
                    TextSize = CalculateAutoFontSize(originalBitmap) // 自动计算字号
                };

                // 测量文本单元尺寸
                var textBounds = new SKRect();
                paint.MeasureText(watermarkText, ref textBounds);
                float unitWidth = textBounds.Width;
                float unitHeight = textBounds.Height;

                // 计算旋转后的覆盖参数
                float rotatedWidth = (float)(unitWidth * Math.Cos(45 * Math.PI / 180)
                                    + unitHeight * Math.Sin(45 * Math.PI / 180));
                float rotatedHeight = (float)(unitWidth * Math.Sin(45 * Math.PI / 180)
                                     + unitHeight * Math.Cos(45 * Math.PI / 180));

                // 全图覆盖算法
                canvas.Save();
                canvas.Translate(originalBitmap.Width / 2f, originalBitmap.Height / 2f);
                canvas.RotateDegrees(45f);

                // 计算覆盖范围（扩大绘制区域）
                float maxDimension = Math.Max(originalBitmap.Width, originalBitmap.Height) * 1.5f;
                int horizontalSteps = (int)(maxDimension / rotatedWidth) + 4;
                int verticalSteps = (int)(maxDimension / rotatedHeight) + 4;

                // 交错偏移参数
                float offsetX = rotatedWidth * 0.5f;
                float offsetY = rotatedHeight * 0.3f;

                // 全图矩阵式绘制
                for (int i = -horizontalSteps; i <= horizontalSteps; i++)
                {
                    for (int j = -verticalSteps; j <= verticalSteps; j++)
                    {
                        // 交错偏移模式
                        float x = i * rotatedWidth + (j % 2) * offsetX;
                        float y = j * rotatedHeight + (i % 2) * offsetY;

                        // 绘制水印单元
                        canvas.DrawText(watermarkText, x, y, paint);

                        // 补充绘制增强覆盖
                        canvas.DrawText(watermarkText, x + offsetX / 2, y + offsetY / 2, paint);
                    }
                }

                canvas.Restore();

                // 转换为显示格式
                using var ms = new MemoryStream();
                bitmap.Encode(ms, SKEncodedImageFormat.Jpeg, 90);
                processedImageData = ms.ToArray();

                PreviewImage.Source = ImageSource.FromStream(() => new MemoryStream(processedImageData));
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"生成失败: {ex.Message}", "确定");
            }
        }

        // 自动计算字号（增加密度控制）
        private float CalculateAutoFontSize(SKBitmap bitmap)
        {
            float densityFactor = 0.05f; // 密度系数（越小越密集）
            float shortSide = Math.Min(bitmap.Width, bitmap.Height);
            return Math.Max(shortSide * densityFactor, 24f);
        }

        private async void Save_Clicked(object sender, EventArgs e)
        {
            if (processedImageData == null)
            {
                await DisplayAlert("提示", "请先生成水印图片", "确定");
                return;
            }

            try
            {
                bool success = false;
                string savedPath = "未知路径";
                string fileName = $"Watermark_{DateTime.Now:yyyyMMddHHmmss}.jpg";

                var devicePlatform = DeviceInfo.Platform;
                if (devicePlatform == DevicePlatform.Android)
                {
#if ANDROID
                        success = await AndroidSaveHelper.SaveToGallery(processedImageData, fileName);
#endif
                    savedPath = "相册";
                }
                else if (devicePlatform == DevicePlatform.iOS)
                {
#if IOS
                    // iOS 保存逻辑
                    NSData nsData = NSData.FromArray(processedImageData);
                    UIImage uiImage = new UIImage(nsData);
                    uiImage.SaveToPhotosAlbum((image, error) =>
                    {
                        if (error != null)
                            Console.WriteLine($"保存失败: {error.LocalizedDescription}");
                    });
                    success = true;
                    savedPath = "相册";
#endif
                }
                else
                {
                    // 桌面端保存到桌面
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    string filePath = Path.Combine(desktopPath, fileName);
                    await File.WriteAllBytesAsync(filePath, processedImageData);
                    success = true;
                    savedPath = filePath;
                }

                if (success)
                {
                    await DisplayAlert("成功", $"图片已保存到：{savedPath}", "确定");
                }
                else
                {
                    await DisplayAlert("失败", "保存失败，请检查权限", "确定");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"保存失败: {ex.Message}", "确定");
            }
        }
    }
}